<template>
    <div class="wrap">
        <div class="head-conditions">
            <el-autocomplete
                    v-model="dynamic.name"
                    :fetch-suggestions="querySearchGoodsNameAsync"
                    placeholder="请输入商品名"
                    @select="handleSelect"
            >
                <i
                        class="el-icon-edit el-input__icon"
                        slot="suffix"
                        @click="handleIconClick">
                </i>
                <template slot-scope="{ item }">
                    <div class="name">{{ item.value }}</div>
                </template>
            </el-autocomplete>

            <el-button type="primary" @click="selectByCondition" icon="el-icon-search"
                       style="float: right;margin-left: 35px">查询
            </el-button>
        </div>
        <div class="head-btns">
            <el-button type="primary" @click="saveNewGoods" icon="el-icon-circle-plus-outline" size="small"
                       style="float: right;margin-right: 8%">新增商品
            </el-button>
        </div>
        <div class="goodsCards">
            <el-col :span="6" v-for="(goods, index) in goodslist" :key="goods.id" :offset="index %3 === 0 ? 1 : 2">
                <el-card class="goods-card" shadow="hover"
                         :body-style="{ padding: '0px'}">
                    <div class="sold-out" v-show="!goods.stock>0">
                        <img style="width: 76px;height: 76px" src="../../assets/icons/soldOut.png"/>
                    </div>
                    <i class="el-icon-close" style="color: #b5bfd0; position: absolute;top: 2%;right: 2%"
                       @click="goRemove(goods.id)"></i>
                    <el-image v-show="goods.imgUrl==null" fit="contain" style="width: 100%;height: 190px">
                        <div slot="error"
                             style="width: 100%;height: 160px; font-size: 50px;color:gray;text-align:center;line-height: 160px;"
                             class="image-slot">
                            <div><i class="el-icon-picture-outline"></i></div>
                        </div>
                    </el-image>
                    <el-image style="width: 100%;height: 195px"
                              :src="goods.imgUrl"
                              fit="fill" class="image" v-show="goods.imgUrl!=null">
                    </el-image>
                    <div style="padding: 14px;">
                        <span>{{goods.name}}</span>
                        <span style="float: right" v-show="goods.stock!==0">库存：{{goods.stock}}</span>
                        <span style="float: right" v-show="goods.stock===0">已售罄</span>
                        <br>
                        <span style="float: left;font-size: 8px;margin-top: 10px">价格:
                            <span style="font-size: 16px;color: #e33636">
                            ￥{{goods.price}}<span
                                    style="text-decoration: line-through;color: #8e9aaf;font-size: 8px;padding-left: 8px">{{(goods.price*1.2).toFixed(1)}}</span>
                                </span>
                        </span>
                        <div class="bottom clearfix">
                            <el-button type="plain" size="mini" icon="el-icon-shopping-cart-2" class="button"
                                       v-show="goods.stock!==0" @click="goOrder(goods)">
                                购买
                            </el-button>
                            <el-button type="plain" size="mini" icon="el-icon-shopping-cart-2" class="button"
                                       disabled v-show="goods.stock===0" @click="goOrder(goods)">
                                购买
                            </el-button>
                            <el-button type="plain" size="mini" icon="el-icon-edit" class="button"
                                       @click="updateGoods(goods)" @updateSuccess="updateSuccess">修改
                            </el-button>

                        </div>
                    </div>
                </el-card>
            </el-col>
        </div>
        <div class="block">
            <el-pagination
                    background
                    @current-change="handleCurrentChange"
                    :current-page.sync="current"
                    :page-size="6"
                    layout="prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <NewGoods :saveNewGoodsShow="saveNewGoodsShow" @cancel="saveNewGoodsShow=false"
                  @saveSuccess="saveSuccess"></NewGoods>
        <update-goods :goods="updateGoodsData" :updateGoodsShow="updateGoodsShow" @cancel="updateGoodsShow=false"
                      @updateSuccess="updateSuccess"/>
        <go-order :goodsOrder="goodsOrder" :orderShow="orderShow" @paySuccess="paySuccess"
                  @cancel="orderShow=false"></go-order>
    </div>
</template>

<script>
    import {PageGoods, getAllGoodsNames} from '@/utils/apis/goods'
    import NewGoods from '@/components/goods/NewGoods'
    import UpdateGoods from "@/components/goods/UpdateGoods";
    import GoOrder from "@/components/goods/GoOrder";
    import {removeGoodsById} from "@/utils/apis/goods";


    export default {
        name: "GoodsList",
        components: {
            GoOrder,
            UpdateGoods,
            NewGoods
        },
        data() {
            return {
                goodslist: [], // 商品列表
                goodsNameOptions: [],//商品名称列表
                total: 0, // 总记录数
                current: 1, // 页码
                dynamic: {
                    name: null
                },
                saveNewGoodsShow: false,
                updateGoodsShow: false,
                updateGoodsData: {},
                orderShow: false,
                goodsOrder: {},
            }
        },
        created() {//页面渲染之前
            this.initData()
        },
        methods: {
            //具体方法
            //初始化数据
            initData() {
                this.handleCurrentChange(1)
                this.getAllGoods()
            },
            //页数切换
            async handleCurrentChange(val) {
                const loading = this.$loading({
                    lock: true,
                    text: '更新数据.......',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })
                this.current = val
                await PageGoods(this.dynamic, this.current, 6).then(res => {
                    this.updateCardData(res)
                    loading.close()
                })
            },
            //更新数据
            updateCardData(val) {
                const data = val.data.data
                this.total = data.total
                this.goodslist = []
                data.records.forEach(g => {
                    this.goodslist.push(g)
                })
            },
            //条件查询
            selectByCondition() {
                if (this.dynamic.name === '')
                    this.dynamic.name = null
                this.current = 1
                PageGoods(this.dynamic, this.current, 6).then(res => {
                    this.updateCardData(res)
                })
            },
            //获取所有商品名称
            getAllGoods() {
                getAllGoodsNames().then(res => [
                    this.goodsNameOptions = res.data.data
                ])
            },
            querySearchGoodsNameAsync(queryString, cb) {
                var goodsNameOptions = this.goodsNameOptions;
                var results = queryString ? goodsNameOptions.filter(this.createDynamicGoodsNameFilter(queryString)) : goodsNameOptions;

                /*clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 3000 * Math.random());*/
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createDynamicGoodsNameFilter(queryString) {
                if (queryString == null)
                    queryString = ''
                return (dynamic) => {
                    console.log(dynamic)
                    return (dynamic.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            handleSelect(item) {
                console.log(item);
            },
            handleIconClick(ev) {
                console.log(ev);
            },
            //添加新器材
            saveNewGoods() {
                this.saveNewGoodsShow = true
            },
            //添加器材成功的回调
            saveSuccess() {
                this.$nextTick(() => {
                    this.handleCurrentChange(this.current)
                })
            },
            //修改器材信息
            updateGoods(goods) {
                this.updateGoodsShow = true
                this.updateGoodsData = JSON.parse(JSON.stringify(goods))
            },
            //修改成功的回调
            updateSuccess() {
                this.$nextTick(() => {
                    this.handleCurrentChange(this.current)
                })
            },

            //去维修
            goOrder(goods) {
                this.goodsOrder = JSON.parse(JSON.stringify(goods))
                this.orderShow = true
            },
            //删除商品数据
            goRemove(id) {
                this.$confirm('此商品的有关信息将被删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    await removeGoodsById(id).then(() => {
                        this.$message.success('删除成功')
                        this.$nextTick(() => {
                            this.handleCurrentChange(this.current)
                        })
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消删除'
                    });
                })
            },
            paySuccess() {
                this.initData()
            },
        }
    }
</script>

<style scoped>
    .wrap {
        height: 84vh;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .head-btns {
        width: 100%;
        height: 22px;
    }

    .goodsCards {
        width: 90%;
        height: 590px;
    }

    .goods-card {
        width: 340px;
        height: 270px;
        border-radius: 10px;
        margin-top: 15px;
        position: relative;
    }

    .bottom {
        float: right;
        width: 165px;
        margin-right: 2px;
        margin-top: 8px;
        line-height: 12px;
        display: flex;
        justify-content: space-between;
    }

    .button {
        /*float: right;*/
    }

    .image {
        width: 100%;
        display: block;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }

    .block {
        margin-top: 15px;
    }

    .el-icon-close {
        cursor: pointer;
        z-index: 2;
    }

    /*    售罄*/
    .sold-out {
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 1;
        background-color: rgba(255, 255, 255, .5);
    }
</style>